package main

import (
	"bytes"
	"encoding/json"
	flag "flag"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
)

var client = &http.Client{}

type Paper struct {
	Path string `json:"path"`
	Name string `json:"name"`
}

type UploadResult struct {
	Name string `json:"name"`
	URL string `json:"url"`
	Suffix string `json:"suffix"`
	FileName string `json:"filename"`
}

type UploadBody struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    []UploadResult `json:"data"`
}

func UploadFile(url string, params map[string]string, nameField string,papers []Paper) ([]byte, error) {

	body := new(bytes.Buffer)
	writer := multipart.NewWriter(body)
	for _,item := range papers {
		file, err := writer.CreateFormFile(nameField, item.Name)
		if err != nil {
			return nil,err
		}
		open, err := os.Open(item.Path)
		if err != nil {
			return nil,err
		}
		_, _ = io.Copy(file, open)
	}

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	err := writer.Close()
	if err != nil {
		return nil,err
	}

	req, err := http.NewRequest("POST", url, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("1,err=",err)
		return nil,err
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return content, nil
}

func main() {
	var Host string
	var Port int
	var UploadSuffix string
	var Name string
	var Scene string

	flag.StringVar(&Host, "h" ,"localhost","上传服务器，默认为localhost")
	flag.IntVar(&Port,"p",8848, "上传服务器，默认8848")
	flag.StringVar(&UploadSuffix, "u", "/upload", "默认上传前缀")
	flag.StringVar(&Name,"n", "file", "上传文件域")
	flag.StringVar(&Scene,"s", "default", "上传文件场景")
	flag.Parse()

	var papers []Paper
	files := flag.Args()
	for _,file := range files {
		stat, err := os.Stat(file)
		if err != nil {
			// 如果文件不存在，直接返回
			return 
		}
		papers = append(papers, Paper{file, stat.Name()})
	}
	params := make(map[string]string)
	params["scene"] = Scene
	url := fmt.Sprintf("http://%s:%d%s", Host,Port, UploadSuffix)
	file, err := UploadFile(url, params, Name, papers)
	if err != nil {
		return
	}

	var ub UploadBody
	_ = json.Unmarshal(file, &ub)
	if len(ub.Data) == len(files) {
		fmt.Println("Upload Success:")
		for index,item := range ub.Data {
			if index == len(ub.Data) - 1 {
				fmt.Print(item.URL)
			} else {
				fmt.Println(item.URL)
			}
		}
	}
}
